package com.company.management.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.management.domain.req.PerformanceEvaluationsReq;
import com.company.management.domain.rsp.PerformanceUserResp;
import com.company.management.domain.rsp.UserResp;
import com.company.management.domain.rsp.UserTreeResp;
import com.company.management.dto.UserDto;
import com.company.management.mapper.PerformanceevaluationUsersMapper;
import com.company.management.modal.entity.PerformanceEvaluationUsers;
import com.company.management.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author robet.li
 * @since 2025-03-02
 */
@Slf4j
@Service
public class PerformanceEvaluationUsersService extends ServiceImpl<PerformanceevaluationUsersMapper, PerformanceEvaluationUsers> {
    @Autowired
    private UserService userService;
    public List<UserTreeResp> getUserList(PerformanceEvaluationsReq req ){
        List<UserResp> userRespList = new ArrayList<>();
        if (req.getEvaluationId() != null && req.getEvaluationId()> 0 ){
            userRespList = this.baseMapper.getAssignUserList(req);
            List<UserTreeResp> userTreeRespList = buildTree(userRespList,true);
            return userTreeRespList;
        }else{
            userRespList = this.baseMapper.getUserList(req);
            return buildTree(userRespList,false);
        }


    }
    private List<UserTreeResp> buildTree(List<UserResp> data,boolean checked) {
        Map<Integer, UserTreeResp> departmentMap = new HashMap<>();
        List<UserTreeResp> result = new ArrayList<>();
        for (UserResp entry : data) {
            // 检查部门是否已存在
            UserTreeResp departmentNode = departmentMap.get(entry.getDeptId());
            if (departmentNode == null) {
                // 如果部门不存在，则创建部门节点
                departmentNode = new UserTreeResp(entry.getDeptId(), entry.getDeptName(),false);
                departmentMap.put(entry.getDeptId(), departmentNode);
                result.add(departmentNode);
            }

            // 添加用户到部门的 children
            if (departmentNode.getChildren() == null) {
                departmentNode.setChildren(new ArrayList<>());
            }
            departmentNode.getChildren().add(new UserTreeResp(entry.getUserId(), entry.getUserName(),checked));
        }

        return result;
    }
    List<PerformanceUserResp> getPerformanceUserList(PerformanceEvaluationsReq req){
        return this.baseMapper.getPerformanceUserList(req);
    }
    public UserDto getUserId(HttpServletRequest request){
        return userService.findUserByToken(ServletUtils.getToken(request));
    }
}
